import java.io.*;
import java.util.*;

import javax.xml.xpath.*;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

public class Presult {

	List resultlist;
	
	
	public Presult(List l)
	{
		resultlist = l;
	}
	
	public Presult(InputStream input)throws Exception
	{
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
		
		XPathFactory factory = XPathFactory.newInstance();
		XPath xPath=factory.newXPath();

		//Get all search Result nodes
		NodeList nodes = (NodeList)xPath.evaluate("/ResultSet/Result", response, XPathConstants.NODESET);
		int nodeCount = nodes.getLength();
        
		resultlist = new ArrayList();
		FileOutputStream oos=new FileOutputStream("Transcript.txt",true);
		for (int i = 0; i < nodeCount; i++) {
			
			String title = (String)xPath.evaluate("Title", nodes.item(i), XPathConstants.STRING);
			String summary = (String)xPath.evaluate("Summary", nodes.item(i), XPathConstants.STRING);
			String url = (String)xPath.evaluate("Url", nodes.item(i), XPathConstants.STRING);
			
			System.out.println(" ----------------  Result " + (i+1)+"  -----------------");
			oos.write((" ----------------  Result " + (i+1)+"  -----------------\n").getBytes());
			System.out.println("Title: " + title);
			oos.write(("Title: " + title+"\n").getBytes());
			System.out.println("Summary: " + summary);
			oos.write(("Summary: " + summary+"\n").getBytes());
			System.out.println("URL: " + url);
			oos.write(("URL: " + url+"\n").getBytes());
			System.out.println(" *******************************************************");
			
			resultlist.add(new Result(title, summary, url));
			
			
		}
		if(resultlist.size()<10){
			System.out.print("The number of results is less than ten, program terminate");System.exit(0);
		  oos.write("The number of results is less than ten, program terminate \n".getBytes())	;
		}
		oos.close();
	}
	
	public Iterator iterator()
	{
		return resultlist.iterator();
	}
	
	public int getSize()
	{
		return resultlist.size();
	}
	
	public Result get(int i)
	{
		return (Result)resultlist.get(i);
	}
}
